#include "global.h"
#include "conn.h"
#include "myfunc.h"
#include "process.h"

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#define HTML_REQ "GET /json/getuser?userId=130000000 HTTP/1.1\r\n" \
					"Host: 10.60.0.11:8002\r\n"\
					"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1\r\n"\
					"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"\
					"Accept-Language: zh-cn,zh;q=0.5\r\n"\
					"Accept-Encoding: gzip,deflate\r\n"\
					"Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7\r\n"\
					"Keep-Alive: 300\r\n"\
					"Connection: keep-alive\r\n"\
					"\r\n"



void* on_request_th(void* param)
{
	pthread_detach( pthread_self() );
	printf("[Syst]on_request_th: Thread on_request_th[%ld:%ld] Start Up\n", (long)getpid(), (long)pthread_self() );

	char * buf = (char *)malloc(1024*16);
	int once= 0;
	while(exit_flag == FRUN)
	{
		printf("I'm on_request_th\n");
		sleep(1);
		strncpy(buf,HTML_REQ,1024*16);
		if(!once){
		printf("sendbuf: %s\n\n\n",buf);
		conn_send(buf,strlen(buf));
		}
		once ++;
		sleep(3);
	}
	free(buf);
	exit_flag ++;
	printf( "[Syst]on_request_th: Thread on_request_th[%ld:%ld] Shut Down\n", (long)getpid(), (long)pthread_self() );
	return 0;
}

void* on_answer_th(void *param)
{
	pthread_detach( pthread_self() );
	printf("[Syst]on_request_th: Thread on_answer_th[%ld:%ld] Start Up\n", (long)getpid(), (long)pthread_self() );

	char * buf = (char *)malloc(1024*16);
	while(exit_flag == FRUN)
	{
		printf("I'm on_answer_th\n");
		sleep(1);
		conn_recv(buf,1024*16);
		printf("recvbuf: %s\n\n\n",buf);
		sleep(3);
	}
	free(buf);
	exit_flag ++;
	printf( "[Syst]on_request_th: Thread on_answer_th[%ld:%ld] Shut Down\n", (long)getpid(), (long)pthread_self() );
	return 0;
}

int init_threads()
{
	int				ret = 0;
	pthread_t		tid;

	ret = pthread_create(&tid, NULL, on_request_th, NULL);
	if (ret != 0){
		printf("[Syst]init_threads: on_request_th Start Failed, ret = %d\n", ret );		
		return -1;
	}	

	ret = pthread_create(&tid, NULL, on_answer_th, NULL);
	if (ret != 0){
		printf("[Syst]init_threads: on_answer_th Start Failed, ret = %d\n", ret );		
		return -2;
	}
	return 0;
}


